<?php


namespace app\common\model\promotion;

use app\common\model\promotion\PromotionRoleModel;
use app\common\model\promotion\PromotionUserAttributesModel;
use think\Model;
use app\common\model\file\FileModel;
use hg\apidoc\annotation as Apidoc;

/**
 * 用户管理模型
 */
class PromotionUserModel extends Model
{
    // 表名
    protected $name = 'promotion_user';
    // 表主键
    protected $pk = 'promotion_user_id';

    // 关联头像文件
    public function avatar()
    {
        return $this->hasOne(FileModel::class, 'file_id', 'avatar_id')->append(['file_url'])->where(where_disdel());
    }
    /**
     * 获取头像链接
     * @Apidoc\Field("")
     * @Apidoc\AddField("avatar_url", type="string", desc="头像链接")
     */
    public function getAvatarUrlAttr()
    {
        return $this['avatar']['file_url'] ?? '';
    }


    // 关联角色
    public function roles()
    {
        return $this->belongsToMany(PromotionRoleModel::class, PromotionUserAttributesModel::class, 'role_id', 'promotion_user_id');
    }
    /**
     * 获取角色id
     * @Apidoc\Field("")
     * @Apidoc\AddField("role_ids", type="array", desc="角色id")
     */
    public function getRoleIdsAttr()
    {
        return relation_fields($this['roles'], 'role_id');
    }
    /**
     * 获取角色名称
     * @Apidoc\Field("")
     * @Apidoc\AddField("role_names", type="string", desc="角色名称")
     */
    public function getRoleNamesAttr()
    {
        return relation_fields($this['roles'], 'role_name', true);
    }

    //生成邀请码
    public function generate_invitation_code($length = 7) {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $charactersLength = strlen($characters);
        $invitation_code = '';
        for ($i = 0; $i < $length; $i++) {
            $invitation_code .= $characters[rand(0, $charactersLength - 1)];
        }
        $info = self::where('invitation_code',$invitation_code)->field('promotion_user_id')->find();
        if($info){
            return self::generate_invitation_code($length);
        }
        return $invitation_code;
    }
}
